import React, { Component } from 'react';
import { Form, Input, Button, Message } from 'element-react';
import { Link } from 'react-router-dom';
import '../login/login.css';
//静态图片必须以此方法引入，并且资源文件夹只能在src下
import Background from '../../static/login_bg.jpg';
const sectionStyle = {
  width: "100%",
  height: "100%",
  overflow: 'hidden',
  // makesure here is String确保这里是一个字符串，以下是es6写法
  backgroundImage: `url(${Background})`,
  backgroundRepeat: 'no-repeat',
  backgroundSize: 'cover',
};
export default class Login extends Component {
  // 数据层
  state = {
    form: {
      phone: '',
      password: '',
    },
    rules: {
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入手机号'));
            } else if (!(/^1[3456789]\d{9}$/.test(value))) {
              callback(new Error('手机号码有误，请重填'));
            } else {
              callback();
            }
          }
        }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入密码'));
            } else {
              callback();
              console.log('验证通过')
            }
          }
        }
      ],


    }
  };
  // 逻辑层
  // 提交表单
  handleSubmit(e) {
    e.preventDefault();
    this.refs.form.validate((valid) => {
      if (valid) {
        this.handleLogin();
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }
  // 登录验证接口
  handleLogin() {
    let that = this;
    let { form } = that.state;
    that.$post(that.$api.login, form).then(res => {
      // console.log(res);
      if (res.code === 200) {
        let userInfor = {
          userId: res.profile.userId,
          nickname: res.profile.nickname,
          token: res.token,
        };
        localStorage.setItem('token', res.token);
        localStorage.setItem('user', JSON.stringify(userInfor));
        console.log(localStorage.getItem('user'))
        Message.success('登录成功！');
        that.props.history.push('/index');
      } else {
        Message.error('错误');
      }
    });
  }
  onChange(key, value) {
    this.setState({
      form: Object.assign({}, this.state.form, { [key]: value }),
    });
  }
  //渲染层
  render() {
    const { form, rules } = this.state;
    return (
      <div style={sectionStyle}>
        <div className="user-wrap">

          <Form ref="form" model={form} rules={rules} labelWidth="0" className="demo-ruleForm">
            <h3>网易云音乐</h3>
            <Form.Item prop="phone">
              <Input value={form.phone} onChange={this.onChange.bind(this, 'phone')} autoComplete="off" placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item prop="password">
              <Input type="password" value={form.password} onChange={this.onChange.bind(this, 'password')} autoComplete="off" placeholder="请输入密码" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={this.handleSubmit.bind(this)}>登录</Button>
            </Form.Item>
            <Form.Item>
              <Link to="/register">没有账号？前往注册</Link >
            </Form.Item>
          </Form>

        </div>
      </div>
    );
  }
}